package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class OrderTradeStrategyContext implements ApplicationContextAware {


    //定义一个实现类对象用户存储 itemType  key数据的类型 value 接口实现类
    private static final Map<String,OrderTradeStrategy> ORDER_TRADE_STRATEGY_MAP = new ConcurrentHashMap<String,OrderTradeStrategy>();



    //为了别人使用我们的策越实现类对象 我们要定义我们的get方法
    public static OrderTradeStrategy getOrderTradeStrategy(String itemType) {
        //存到了map里面从map里面获取
        return ORDER_TRADE_STRATEGY_MAP.get(itemType);
    }


    //将容器交付给spring,为了获取这些容器 实现ApplicationContextAware@Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, OrderTradeStrategy> beansOfType = applicationContext.getBeansOfType(OrderTradeStrategy.class);  //这里的beansType是管理的三个实现类
        //从实现类中抽取我们的itemType 放到我们的map里面
        beansOfType.values().forEach(orderTradeStrategy -> {
            String itemType = orderTradeStrategy.getItemType();  //获取接口的付款项目类型
            ORDER_TRADE_STRATEGY_MAP.put(itemType,orderTradeStrategy);
        });
    }

   /* private static  final Map<String,OrderTradeStrategy> ORDER_TRADE_STRATEGY_MAP = new ConcurrentHashMap<String, OrderTradeStrategy>();


    // 根据付款项目的类型获取对应的策略实现类对象
    public static OrderTradeStrategy getOrderTradeStrategy(String itemType) {
        //itemType什么类型 获取什么样的实现类对象
        return ORDER_TRADE_STRATEGY_MAP.get(itemType) ;
    }
    //获取全部的实现类对象 map.put
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        *//*
        * Map的键是bean的名称，值就是OrderTradeStrategy接口的实现类型对象
        * *//*
        Map<String,OrderTradeStrategy> beansOfType = applicationContext.getBeansOfType(OrderTradeStrategy.class);
        beansOfType.values().forEach(orderTradeStrategy -> {
            String itemType = orderTradeStrategy.getItemType();
            ORDER_TRADE_STRATEGY_MAP.put(itemType,orderTradeStrategy);
        });
    }*/




}
